package com.leaves.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.spring.SpringMVCUtil;
import com.leaves.response.ApiResult;
import com.leaves.response.ApiResultConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2021年06月21日 10时28分24秒
 * @Description: sa-token异常处理
 */
@ResponseBody
@ControllerAdvice
public class SaTokenException {

    private Logger logger = LoggerFactory.getLogger(SaTokenException.class);

    // 全局异常拦截（拦截项目中的NotLoginException异常）

    @ExceptionHandler(NotLoginException.class)
    public ApiResult handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //// 打印堆栈，以供调试
        logger.error("---------------全局异常拦截---------------");
        nle.printStackTrace();
        SpringMVCUtil.getResponse().setStatus(ApiResultConstant.CODE_NOT_LOGIN);
        // 判断场景值，定制化异常信息
        String message = "";
        String type = nle.getType();
        if (NotLoginException.NOT_TOKEN.equals(type)) {
            logger.error("NotLoginException.NOT_TOKEN = " + NotLoginException.NOT_TOKEN);
            message = "您的令牌为空";
        } else if (NotLoginException.INVALID_TOKEN.equals(type)) {
            logger.error("NotLoginException.INVALID_TOKEN = " + NotLoginException.INVALID_TOKEN);
            message = "您的令牌无效";
        } else if (NotLoginException.TOKEN_TIMEOUT.equals(type)) {
            logger.error("NotLoginException.TOKEN_TIMEOUT = " + NotLoginException.TOKEN_TIMEOUT);
            message = "您的令牌已过期";
        } else if (NotLoginException.BE_REPLACED.equals(type)) {
            logger.error("NotLoginException.BE_REPLACED = " + NotLoginException.BE_REPLACED);
            message = "账号在别处登录，请注意是否为您本人操作";
        } else if (NotLoginException.KICK_OUT.equals(type)) {
            logger.error("NotLoginException.KICK_OUT = " + NotLoginException.KICK_OUT);
            message = "您已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        // 返回给前端
        return ApiResult.error(message);
    }

}
